package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public String login(User user) {
        String password=user.getPassword();
        byte[] bytes = password.getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Password);
        User userDB=userMapper.findUserByUP(user);
        if (userDB ==null){
            return null;
        }
        String token= UUID.randomUUID().toString();
        return token;
    }

    /**
     * 分页
     * @param pageResult
     * @return
     */
    @Override
    public PageResult findUserList(PageResult pageResult) {
        //1.total
        long total = userMapper.findTotal();
        //2.rows
        int start = (pageResult.getPageNum()-1)* pageResult.getPageSize();
        int size=pageResult.getPageSize();
        String query=pageResult.getQuery();
        List<User> rows=userMapper.findUserList(query,start,size);
        pageResult.setTotal(total).setRows(rows);
        return pageResult;
    }

    /**
     * 修改状态
     * @param user
     */
    @Override
    @Transactional
    public void updateStatus(User user) {
        user.setUpdated(new Date());
        userMapper.updateStatus(user);
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }

    /**
     * 用户新增
     * @param user
     */
    @Override
    @Transactional
    public void saveUser(User user) {
        String password= user.getPassword();
        String md5Password=DigestUtils.md5DigestAsHex(password.getBytes());
        user.setStatus(true).setPassword(md5Password).setCreated(new Date()).setUpdated(new Date());
        userMapper.saveUser(user);
    }

    /**
     * 用户修改--数据回显
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {
        User user = userMapper.findUserById(id);
        return user;
    }

    /**
     * 用户修改--数据提交
     * @param user
     */
    @Override
    @Transactional
    public void updateUser(User user) {
        user.setUpdated(new Date());
        userMapper.updateUser(user);
    }


}
